import Vue from 'vue'
import { install, Store } from 'vuex'

install(Vue)

export default new Store({
    state: {
        appkey: 'Jia-Hui00_1635520418379',
        goods_count: 0,
        shopping_cart: {},
        search_words: []
    },
    mutations: {
        init_data(state) {
            // 初始化数据
            const shopping_cart = localStorage.getItem('shopping_cart') || '{}'
            state.shopping_cart = JSON.parse(shopping_cart)
            state.goods_count = Object.keys(state.shopping_cart).length

            const search_words = localStorage.getItem('search_words') || '[]'
            state.search_words = JSON.parse(search_words)
        },
        set_appkey(state, key) {
            state.appkey = key
            // 设置完 appkey 后，将购物车和搜索词清空
            state.shopping_cart = {}
            state.search_words = []
            state.goods_count = 0
        },
        set_shopping_cart(state, goods) {
            if (goods.count) {
                state.shopping_cart[goods.id] = goods.count
            } else {
                delete state.shopping_cart[goods.id]
            }
            state.goods_count = Object.keys(state.shopping_cart).length
        },
        del_goods(state, id_list) {
            for (const id of id_list) {
                delete state.shopping_cart[id]
            }
            state.goods_count = Object.keys(state.shopping_cart).length
        },
        set_search_words(state, words) {
            state.search_words = words
        }
    }
})
